# %%

import pyfolio as pf
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import json
import warnings
warnings.filterwarnings('ignore')
bitcoin_strategy_backtest = pd.read_csv('bitcoin_strategy_backtest.csv', index_col=0, parse_dates=True)
returns = bitcoin_strategy_backtest['returns']
#print(returns.head())
pf.create_returns_tear_sheet(returns)

# 获取当前的 Figure 对象
fig = plt.gcf()

# 获取 Figure 中的所有 Axes 对象 (子图)
axes = fig.get_axes()

# 定义要修改的子图数量（前 8 个）
num_axes_to_modify = min(8, len(axes)) # 确保不会超出实际的 Axes 数量

# 遍历前 num_axes_to_modify 个 Axes 并修改 X 轴
for i, ax in enumerate(axes[:num_axes_to_modify]):
    try:
        # 设置主刻度定位器为年份
        ax.xaxis.set_major_locator(mdates.YearLocator())
        # 设置主刻度格式化器为 '%Y' (四位数年份)
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
        # 旋转刻度标签以防重叠
        plt.setp(ax.xaxis.get_majorticklabels(), rotation=45, ha='right')
    except Exception as e:
        print(f"无法修改第 {i+1} 个图的 X 轴: {e}") # 添加错误处理，以防某些子图类型不支持此操作

# 调整布局防止标签重叠
plt.tight_layout()

# %%
bitcoin_strategy_backtest['positions'] = bitcoin_strategy_backtest['positions'].apply(lambda x: x.replace("'", '"'))
bitcoin_strategy_backtest['transactions'] = bitcoin_strategy_backtest['transactions'].apply(lambda x: x.replace("'", '"'))
bitcoin_strategy_backtest['transactions'] = bitcoin_strategy_backtest['transactions'].apply(lambda x: x.replace("datetime.", '"datetime.'))
bitcoin_strategy_backtest['transactions'] = bitcoin_strategy_backtest['transactions'].apply(lambda x: x.replace(")", ')"'))

positions = bitcoin_strategy_backtest[['positions', 'ending_cash']]
position_data = json.loads(positions.iloc[1, 0])

symbol = position_data[0]['symbol']
positions_edited = pd.DataFrame(0, index = positions.index, columns = [[symbol, 'cash']])
for index, row in positions.iterrows():
    position_data = json.loads(row['positions'])

    if position_data:
        positions_edited.loc[index, symbol] = position_data[0]['amount']   
    positions_edited.loc[index, 'cash'] = int(row['ending_cash'])
print(positions_edited.head()) 

transactions = bitcoin_strategy_backtest[['transactions']]
transactions_edited = pd.DataFrame(np.nan, index = transactions.index, columns = [['amount', 'price', 'symbol']])
transactions_edited['symbol'] = transactions_edited['symbol'].astype(str)

for index, row in transactions.iterrows():
    #print('index: ', index, "row['transactions']: ", row['transactions'])
    transactions_data = json.loads(row['transactions'])
    if transactions_data:
        transactions_edited.loc[index, 'price'] = float(transactions_data[0]['price'])   
        transactions_edited.loc[index, 'amount'] = transactions_data[0]['amount']           
        transactions_edited.loc[index, 'symbol'] = symbol
    else:
        transactions_edited.loc[index, 'price'] = 0
        transactions_edited.loc[index, 'amount'] = 0
        transactions_edited.loc[index, 'symbol'] = symbol   
transactions_edited = transactions_edited.dropna()
print(transactions_edited.dtypes)

#pf.create_full_tear_sheet(returns,
#                          positions=positions_edited,
#                          transactions=transactions_edited,
#                         slippage=1)
plt.show()

# %%
